package com.littlebee.storysuper.activity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.littlebee.storysuper.R;
import com.littlebee.storysuper.entry.EnglishEntry;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.widget.CircleImageView;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 相册 or  英语
 */
public class EnglishActivity extends BaseActivity implements View.OnClickListener{
    /** 0 英语  1 相册*/
    private int type;
    private GridView gridView;
    private CommonAdapter<String> mAdapter;
    ArrayList<String> names=new ArrayList<String>();

    /**是否在播放*/
    private boolean isPlaying;
    /**播放进度*/
    private int currPost=0;
    /**用于做延迟加载*/
    private Handler handler=null;
    /**播放条目的下标*/
    private int diversityIndex=0;

    /** 视频播放组件*/
    private VideoView videoView;
    /**播放or暂停annual */
    private ImageView playPauseIv;
    /** 播放进度*/
    private TextView nowProgressTv;
    /** 播放进度条 */
    private SeekBar progressBar;
    /** 总进度*/
    private TextView totalLengthTv;
    /** 全屏*/
    private ImageView fullScreenIv;
    /** 选集浮动层*/
    private FrameLayout diversityFy;
    /** 选集列表*/
    private GridView diversityGv;
    /**播放以前的初始化图片*/
    private ImageView videoInitIv;
    /**视频标题*/
    private TextView videoTitleTv;
    /**分集评论数据*/
    ArrayList<EnglishEntry> diversityDatas = new ArrayList<>();

    @Override
    public int getLayoutResId() {
        return R.layout.activity_english;
    }

    @Override
    public void initView() {
        super.initView();
        handler=new Handler();
        type=getIntent().getIntExtra("type",0);
        gridView=(GridView) findViewById(R.id.listView);
        videoInitIv=(ImageView)findViewById(R.id.init_video_iv);
        videoTitleTv=(TextView)findViewById(R.id.video_title_tv);

        videoView=(VideoView) findViewById(R.id.video_view);
        playPauseIv=(ImageView) findViewById(R.id.play_pause_iv);
        nowProgressTv=(TextView) findViewById(R.id.now_progress_tv);
        progressBar=(SeekBar) findViewById(R.id.progressBar);
        totalLengthTv=(TextView)findViewById(R.id.total_length_tv);
        playPauseIv.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        for (int i=0;i<12;i++) {
            //String content, String time, String index, String path
            EnglishEntry mediaDiversityEntry = new EnglishEntry("英语"+i,"英语标题"+i,""+i,"http://v.cctv.com/flash/mp4video6/TMS/2011/01/05/cf752b1c12ce452b3040cab2f90bc265_h264818000nero_aac32-1.mp4");
            diversityDatas.add(mediaDiversityEntry);
        }
        for (int i=0;i<20;i++){
            if(type==0) {
                names.add("幼儿英语" + i);
            }else{
                names.add("宝宝相册" + i);

            }

        }
        mAdapter = new CommonAdapter<String>(getActivity(), R.layout.layout_item_story) {
            @Override
            protected void convert(ViewHolder viewHolder, final String workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                CircleImageView iv = viewHolder.findViewById(R.id.photo);

                name.setText(workerListEntry);
            }
        };
        gridView.setAdapter(mAdapter);
        mAdapter.addAll(names);


    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        if(type==0) {

            toolbar.setTitle(getString(R.string.boby_eng_txt));
        }else{
            toolbar.setTitle(getString(R.string.boby_photo_txt));

        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play_pause_iv:
                if(videoView != null && videoView.isPlaying()){
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                    currPost=videoView.getCurrentPosition();
                    videoView.pause();
                    isPlaying=false;
                }else{
                    videoInitIv.setVisibility(View.GONE);
                    videoTitleTv.setVisibility(View.GONE);
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);
                    play(diversityDatas.get(diversityIndex).getPath(),currPost);
                }
                break;
        }
    }

    private void initPlayer(int diversityIndex, int currPost) {
        videoInitIv.setVisibility(View.GONE);
        videoTitleTv.setVisibility(View.GONE);

        playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);

        videoTitleTv.setText(diversityDatas.get(diversityIndex).getContent());
        play(diversityDatas.get(diversityIndex).getPath(),currPost);
    }
    private SeekBar.OnSeekBarChangeListener change=new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView != null && videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
                //修改时间
            }
        }
    };

    /**
     * 播放咯
     * @param path 地址
     * @param msec 播放进度
     */
    protected void play(String path,int msec) {
        //获取视频文件地址

        videoView.setVideoURI(Uri.parse(path));
        LogUtils.i("XHX","初始化播放器了");
        //开始播放
        videoView.start();

        // 按照初始位置播放
        videoView.seekTo(msec);

        //修改时间
        // 开始线程，更新进度条的刻度
        new Thread() {
            @Override
            public void run() {
                try {
                    isPlaying = true;
                    while (isPlaying) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition();
                        progressBar.setMax(videoView.getDuration());
                        progressBar.setProgress(current);
                        handler.post(runnableUi);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调 续播还是结束播放
                if(diversityIndex<diversityDatas.size()-1){
                    diversityIndex+=1;
                    currPost=0;
                    videoTitleTv.setText(diversityDatas.get(diversityIndex).getContent());
                    play(diversityDatas.get(diversityIndex).getPath(),currPost);
                }else{
                    videoInitIv.setVisibility(View.VISIBLE);
                    videoTitleTv.setVisibility(View.VISIBLE);
                }
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //TODO  发生错误重新播放
                play(diversityDatas.get(0).getPath(),0);
                isPlaying = false;
                return false;
            }
        });
    }
    // 构建Runnable对象，在runnable中更新界面
    Runnable   runnableUi=new  Runnable(){
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            if(videoView.getDuration()!=-1) {
                totalLengthTv.setText(DateUtils.getTimeString(videoView.getDuration()));
            }
            nowProgressTv.setText(DateUtils.getTimeString(videoView.getCurrentPosition()));

        }

    };
}
